package com.hncboy.chatgpt.front.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hncboy.chatgpt.base.domain.entity.FrontUserBaseDO;
import com.hncboy.chatgpt.front.service.FrontUserBaseService;
import com.hncboy.chatgpt.front.util.FrontUserUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.hncboy.chatgpt.front.api.config.PayConstants.*;

@RestController
@RequestMapping("/notify")
public class NotifyController {

    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();

    @Resource
    private FrontUserBaseService baseUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/alipay")
    public String handleAlipayNotify(@RequestParam Map<String, String> params) throws AlipayApiException {
        boolean isVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE);
        if (isVerified) {
            // 根据支付结果进行相应的业务处理
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");
            String totalAmount = params.get("total_amount");
            //从Redis找 对应的订单 如果没有通知 支付宝无需回调
            String key = outTradeNo;
            String value = stringRedisTemplate.opsForValue().get(key);
            if (value == null) {
                //无需回调通知
                return "fail";
            }

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                System.out.println("回调成功");
                // TODO: 更新订单状态，发货等操作

                String input = totalAmount;
                int total = (int) Double.parseDouble(input);
                System.out.println("充值金额:"+total);
                int userid = Integer.parseInt(value);
                System.out.println("String 转 int" + userid);
                updateOrderStatus(outTradeNo, total, userid);
                SseEmitter emitter = emitters.remove(outTradeNo);
            } else if ("TRADE_CLOSED".equals(tradeStatus)) {
                System.out.println("回调失败");
                // TODO: 更新订单状态或者做其他相应处理
            }
            return "success";
        } else {
            // 验证签名失败
            return "fail";
        }
    }

    // 更新订单状态
    private void updateOrderStatus(String outTradeNo, int total, int userid) {
        // TODO: 实现订单状态更新逻辑
        //从前端传递UserId获取哪个用户充值的
        FrontUserBaseDO user = baseUserService.findUserInfoById(userid);
        Integer count = Integer.valueOf(user.getCount());
        System.out.println(count);
        int addCount = total * 20; // 默认1元充值10次
        // 将 count 加上充值金额兑换的次数
        user.setCount(count + addCount);
        // 调用 updateCountById() 方法更新到数据库中
        baseUserService.updateCountById(user.getId(), user.getCount());
        System.out.println("余额充值成功");
        // 将消息发送到客户端
        SseEmitter emitter = new SseEmitter();
        emitters.put(outTradeNo, emitter);
        try {
            emitter.send(user.getCount());
            emitter.send(user.getId());
            emitter.send(outTradeNo);
            // 可以发送多条消息
            emitter.send("订单已完成");
            emitter.complete();
        } catch (IOException e) {
            // 异常处理
        }
    }
}
